<template>
  <div class="home-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="user-profile" @click="showProfile = true">
        <div class="avatar">
          <el-avatar :size="50" :src="userInfo.avatar" />
        </div>
        <div class="user-info">
          <div class="nickname">{{ userInfo.nickname }}</div>
          <div class="tf-id">TF ID: {{ userInfo.tfId }}</div>
        </div>
      </div>

      <el-menu
        :default-active="activeMenu"
        class="menu"
        @select="handleMenuSelect"
      >
        <el-menu-item index="friends">
          <el-icon><ChatDotRound /></el-icon>
          <span>我的好友</span>
        </el-menu-item>
        <el-menu-item index="groups">
          <el-icon><Service /></el-icon>
          <span>我的群组</span>
        </el-menu-item>
        <el-menu-item index="contacts">
          <el-icon><User /></el-icon>
          <span>通讯录</span>
        </el-menu-item>
        <el-menu-item index="settings">
          <el-icon><Setting /></el-icon>
          <span>设置</span>
        </el-menu-item>
      </el-menu>

      <div class="logout" @click="handleLogout">
        <el-icon><SwitchButton /></el-icon>
        <span>退出登录</span>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 好友列表 -->
      <div v-if="activeMenu === 'friends'" class="friend-list">
        <div class="friend-list-header">
          <div class="friend-actions-header">
            <el-button 
              type="primary" 
              size="small" 
              @click="showSearchUserDialog = true" 
              icon="Plus"
            >
              添加好友
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="viewFriendRequests"
              class="friend-request-btn"
            >
              好友请求
              <template v-if="friendRequestCount > 0">
                <el-badge :value="friendRequestCount" class="request-badge" type="danger" />
              </template>
            </el-button>
          </div>
          <div class="friend-search">
            <el-input
              v-model="friendSearchQuery"
              placeholder="搜索好友"
              clearable
              size="small"
              :prefix-icon="Search"
            />
          </div>
        </div>
        
        <div 
          v-loading="loading" 
          element-loading-text="加载中..."
          class="friend-list-content"
        >
          <div
            v-for="friend in filteredFriends"
            :key="friend.id"
            :class="['friend-item', selectedFriend && selectedFriend.userId === friend.userId ? 'active' : '']"
            @click="selectFriend(friend)"
          >
            <div class="avatar-container">
              <el-avatar :size="50" :src="friend.avatar" />
              <div v-if="unreadMessages[friend.userId] && unreadMessages[friend.userId] > 0" class="unread-badge">
                <el-badge :value="unreadMessages[friend.userId]" type="danger" />
              </div>
            </div>
            <div class="friend-info">
              <div class="friend-name">{{ friend.remark || friend.nickname }}</div>
              <div class="friend-status">{{ friend.signature || '暂无消息' }}</div>
            </div>
            <div class="friend-actions">
              <el-dropdown trigger="click" @command="handleFriendCommand($event, friend)">
                <div class="friend-more" @click.stop>
                  <el-icon><MoreFilled /></el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="detail">查看资料</el-dropdown-item>
                    <el-dropdown-item command="remark">修改备注</el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除好友</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <!-- 加载更多 -->
          <div v-if="pagination.total > friendList.length" class="load-more">
            <el-button @click="loadMoreFriends" :loading="loading" text>加载更多</el-button>
          </div>
          
          <!-- 无好友时显示 -->
          <el-empty v-if="friendList.length === 0 && !loading" description="暂无好友">
            <el-button type="primary" size="small" @click="showAddFriendDialog = true">添加好友</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 聊天内容区 -->
      <div v-if="selectedFriend && activeMenu === 'friends'" class="chat-area">
        <div class="chat-header">
          <div class="chat-title">{{ selectedFriend.remark || selectedFriend.nickname }}</div>
          <div class="chat-toolbar">
            <el-icon><VideoCameraFilled /></el-icon>
            <el-icon><Phone /></el-icon>
            <el-icon><MoreFilled /></el-icon>
          </div>
        </div>
        <div class="chat-messages" v-loading="messageLoading" @scroll="handleChatScroll">
          <div v-if="messageList.length === 0" class="chat-placeholder">
            <el-empty description="暂无聊天记录" />
          </div>
          <div v-else class="message-list">
            <!-- 加载更多提示 -->
            <div v-if="messagePagination.hasMore" class="load-more-messages">
              <div v-if="messageLoading" class="loading-indicator">
                <el-icon class="loading-icon"><Loading /></el-icon>
                加载更多消息...
              </div>
              <div v-else @click="loadMoreMessages" class="load-more-btn">
                点击加载更多
              </div>
            </div>
            
            <div 
              v-for="message in messageList" 
              :key="message.id"
              :class="['message-item', message.senderUserId == userInfo.id ? 'self' : 'other']"
            >
              <el-avatar 
                :size="40" 
                :src="message.senderUserId == userInfo.id ? userInfo.avatar : selectedFriend.avatar" 
              />
              <div class="message-content">
                <!-- 不同类型的消息显示不同内容 -->
                <div v-if="message.msgType === MessageType.TEXT" class="message-text">
                  {{ message.content }}
                </div>
                
                <!-- 图片消息 -->
                <div v-else-if="message.msgType === MessageType.IMAGE" class="message-image">
                  <el-image 
                    :src="message.content" 
                    :preview-src-list="[message.content]"
                    fit="cover"
                    :initial-index="0"
                    preview-teleported
                    style="max-width: 200px; max-height: 200px; border-radius: 8px;"
                  />
                </div>
                
                <!-- 文件消息 -->
                <div v-else-if="message.msgType === MessageType.FILE" class="message-file">
                  <div class="file-container" @click="downloadFile(message.content, message.fileName)">
                    <el-icon><Document /></el-icon>
                    <div class="file-info">
                      <div class="file-name">{{ message.fileName || '未命名文件' }}</div>
                      <div class="file-size" v-if="message.fileSize">{{ formatFileSize(message.fileSize) }}</div>
                    </div>
                    <el-icon><Download /></el-icon>
                  </div>
                </div>
                
                <div class="message-time">
                  {{ formatDate(message.createTime) }}
                  <span 
                    v-if="message.senderUserId == userInfo.id" 
                    class="read-status"
                    :data-read="message.status === 1"
                  >
                    {{ message.status === 1 ? '已读' : '未读' }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-input-area">
          <div class="toolbar">
            <el-upload
              class="upload-button"
              action="#"
              :show-file-list="false"
              :before-upload="handleUploadImage"
              accept="image/*"
            >
              <el-icon title="发送图片"><PictureFilled /></el-icon>
            </el-upload>
            <el-upload
              class="upload-button"
              action="#"
              :show-file-list="false"
              :before-upload="handleUploadFile"
              accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar"
            >
              <el-icon title="发送文件"><Paperclip /></el-icon>
            </el-upload>
            <el-icon><Microphone /></el-icon>
          </div>
          <el-input
            v-model="messageText"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            resize="none"
            @keydown.enter.prevent="sendMessage"
          />
          <el-button type="primary" :disabled="!messageText.trim()" @click="sendMessage">
            发送
          </el-button>
        </div>
      </div>

      <!-- 搜索结果区域 -->
      <div v-if="searchResult && activeMenu === 'friends'" class="search-result-area">
        <div class="search-result-content">
          <div class="search-result-header">
            <h3>搜索结果</h3>
            <el-button type="primary" size="small" @click="searchResult = null">返回</el-button>
          </div>
          <div class="search-result-item">
            <el-avatar :size="60" :src="searchResult.avatar" />
            <div class="search-result-info">
              <div class="search-result-name">
                {{ searchResult.nickname }}
                <span class="search-result-tfid">TF ID: {{ searchResult.tfId }}</span>
              </div>
              <div class="search-result-email">{{ searchResult.email }}</div>
              <div class="search-result-signature">{{ searchResult.signature || '这个人很懒，什么都没留下' }}</div>
              <div class="search-result-actions">
                <el-button 
                  v-if="(!searchResult.isFriend || searchResult.isFriend === 2) && searchResult.id !== userInfo.id" 
                  type="primary" 
                  size="small" 
                  @click="handleAddFriend(searchResult)"
                >
                  {{ searchResult.isFriend === 2 ? '再次发送请求' : '添加好友' }}
                </el-button>
                <el-tag v-else-if="searchResult.isFriend === 1" type="success" size="small">已是好友</el-tag>
                <el-tag v-else type="info" size="small">这是你自己</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空白状态 -->
      <div v-if="!selectedFriend && !searchResult && activeMenu === 'friends'" class="empty-chat">
        <div class="empty-chat-content">
          <el-icon :size="64" class="empty-icon"><ChatLineRound /></el-icon>
          <p>选择一位好友开始聊天</p>
        </div>
      </div>

      <!-- 其他菜单项的内容 -->
      <div v-if="activeMenu !== 'friends'" class="placeholder-content">
        <el-empty :description="`${menuLabels[activeMenu]}功能即将上线`" />
      </div>
    </div>

    <!-- 个人资料弹窗 -->
    <el-dialog
      v-model="showProfile"
      title="我的个人资料"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div v-loading="loading" class="profile-content">
        <div class="profile-avatar">
          <el-avatar :size="100" :src="userInfo.avatar" />
          <div class="avatar-upload">
            <el-button size="small" type="primary" @click="uploadAvatar">更换头像</el-button>
          </div>
        </div>

        <el-form 
          ref="profileFormRef" 
          :model="userProfile" 
          :rules="profileRules" 
          label-width="90px"
        >
          <el-form-item label="TF ID" prop="tfId">
            <el-input v-model="userProfile.tfId" placeholder="请输入TF ID" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="userProfile.nickname" placeholder="请输入昵称" maxlength="20" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userInfo.email" disabled />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="userProfile.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="搜索设置" prop="searchEnabled">
            <el-radio-group v-model="userProfile.searchEnabled">
              <el-radio :label="1">可被搜索</el-radio>
              <el-radio :label="0">不可被搜索</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="个性签名" prop="signature">
            <el-input
              v-model="userProfile.signature"
              type="textarea"
              :rows="3"
              placeholder="请输入个性签名"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showProfile = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="saveProfile">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 好友详情弹窗 -->
    <el-dialog
      v-model="showFriendDetail"
      title="好友详情"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div v-loading="loadingFriendDetail" class="friend-detail-content">
        <div class="friend-detail-avatar">
          <el-avatar :size="100" :src="friendDetail?.avatar" />
        </div>

        <div class="friend-detail-info">
          <div class="detail-item">
            <span class="label">TF ID:</span>
            <span class="value">{{ friendDetail?.tfId }}</span>
          </div>
          <div class="detail-item">
            <span class="label">昵称:</span>
            <span class="value">{{ friendDetail?.nickname }}</span>
          </div>
          <div class="detail-item">
            <span class="label">邮箱:</span>
            <span class="value">{{ friendDetail?.email }}</span>
          </div>
          <div class="detail-item">
            <span class="label">性别:</span>
            <span class="value">
              {{ friendDetail?.gender === 1 ? '男' : (friendDetail?.gender === 2 ? '女' : '保密') }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">备注:</span>
            <span class="value">{{ friendDetail?.remark || '无' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">个性签名:</span>
            <span class="value">{{ friendDetail?.signature || '这个人很懒，什么都没留下' }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showFriendDetail = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加好友弹窗 -->
    <el-dialog
      v-model="showSearchUserDialog"
      title="添加好友"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div v-if="!searchResult" class="search-user-form">
        <p class="search-tip">通过TF ID或邮箱查找用户</p>
        <el-input
          v-model="searchQuery"
          placeholder="输入TF ID或邮箱"
          clearable
          class="search-input"
          :prefix-icon="Search"
        >
          <template #append>
            <el-button :loading="searchLoading" @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <div v-if="searchResult" class="search-result-container">
        <div class="search-result-user">
          <el-avatar :size="60" :src="searchResult.avatar" />
          <div class="search-result-info">
            <div class="search-result-name">
              {{ searchResult.nickname }}
              <span class="search-result-tfid">TF ID: {{ searchResult.tfId }}</span>
            </div>
            <div class="search-result-email">{{ searchResult.email }}</div>
            <div class="search-result-signature">{{ searchResult.signature || '这个人很懒，什么都没留下' }}</div>
          </div>
        </div>
        
        <div class="search-result-actions">
          <el-button 
            v-if="(!searchResult.isFriend || searchResult.isFriend === 2) && searchResult.id !== userInfo.id" 
            type="primary" 
            @click="handleAddFriend(searchResult)"
          >
            {{ searchResult.isFriend === 2 ? '再次发送请求' : '添加好友' }}
          </el-button>
          <el-tag v-else-if="searchResult.isFriend === 1" type="success">已是好友</el-tag>
          <el-tag v-else type="info">这是你自己</el-tag>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeSearchDialog">{{ searchResult ? '返回搜索' : '取消' }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User, Setting, ChatDotRound, Service, SwitchButton,
  Search, Phone, VideoCameraFilled, MoreFilled, ChatLineRound,
  PictureFilled, Paperclip, Microphone, Loading, Plus, Document, Download
} from '@element-plus/icons-vue'
import { getUserInfo, updateProfile } from '@/api/user'
import { getFriendList, searchFriend, addFriend, getFriendRequests, handleFriendRequest, deleteFriend, updateFriendRemark, getFriendInfo } from '@/api/friend'
import { closeWebSocket, addMessageListener, removeMessageListener } from '@/utils/websocket'
import { sendMessageRequest, getMessageList, markMessagesAsRead, getUnreadMessageCount, MessageType } from '@/api/message'
import { uploadImage, uploadFile, getFileUrl } from '@/api/file'
import PinyinMatch from 'pinyin-match'

export default {
  name: 'HomePage',
  components: {
    User, Setting, ChatDotRound, Service, SwitchButton,
    Search, Phone, VideoCameraFilled, MoreFilled, ChatLineRound,
    PictureFilled, Paperclip, Microphone, Loading, Plus, Document, Download
  },
  setup() {
    const router = useRouter()
    const activeMenu = ref('friends')
    const showProfile = ref(false)
    const selectedFriend = ref(null)
    const searchQuery = ref('')
    const messageText = ref('')
    const loading = ref(true)
    const profileFormRef = ref(null)
    const showAddFriendDialog = ref(false)
    const searchResult = ref(null)
    const searchLoading = ref(false)
    const friendSearchQuery = ref('')
    const showSearchUserDialog = ref(false)

    // 分页参数
    const pagination = reactive({
      page: 1,
      size: 20,
      total: 0
    })

    // 用户信息
    const userInfo = reactive({
      id: '',
      email: '',
      tfId: '',
      nickname: '加载中...',
      avatar: 'https://avatars.githubusercontent.com/u/29829757',
      gender: 1,
      searchEnabled: 1,
      signature: ''
    })

    // 用于编辑的个人资料
    const userProfile = reactive({
      tfId: '',
      nickname: '',
      avatar: '',
      gender: 1,
      searchEnabled: 1,
      signature: '这个人很懒，什么都没留下'
    })

    // 好友列表
    const friendList = ref([])

    // 好友请求列表
    const friendRequests = ref([])
    const requestLoading = ref(false)
    
    // 消息记录
    const messageList = ref([])
    const messageLoading = ref(false)
    
    // 消息分页参数
    const messagePagination = reactive({
      page: 1,
      size: 20,
      hasMore: true
    })
    
    // 未读消息计数
    const unreadMessages = ref({})  // 格式: { userId: count }

    // 菜单标签映射
    const menuLabels = {
      friends: '我的好友',
      groups: '我的群组',
      contacts: '通讯录',
      settings: '设置'
    }

    // 好友请求数量
    const friendRequestCount = ref(0)

    // 好友详情数据
    const friendDetail = ref(null)
    const showFriendDetail = ref(false)
    const loadingFriendDetail = ref(false)

    // 定时器引用
    let requestCheckTimer = null;

    // 获取好友列表
    const fetchFriends = async () => {
      try {
        loading.value = true
        const result = await getFriendList(pagination.page, pagination.size)
        console.log('获取到的好友列表:', result)
        
        // 分析好友列表中的userId字段
        if (result.records && result.records.length > 0) {
          console.log('第一个好友对象:', result.records[0])
          console.log('好友ID类型检查:')
          result.records.forEach((friend, index) => {
            console.log(`好友[${index}] - userId: ${friend.userId}, 类型: ${typeof friend.userId}`)
          })
        }
        
        friendList.value = result.records || []
        pagination.total = result.total || 0
      } catch (error) {
        console.error('获取好友列表失败:', error)
        // API层已经显示了错误消息
      } finally {
        loading.value = false
      }
    }

    // 过滤好友列表
    const filteredFriends = computed(() => {
      if (!friendSearchQuery.value) return friendList.value
      
      const query = friendSearchQuery.value.toLowerCase();
      
      return friendList.value.filter(friend => {
        // 直接匹配（区分大小写）
        const directMatch = 
          friend.nickname.toLowerCase().includes(query) || 
          (friend.remark && friend.remark.toLowerCase().includes(query));
          
        // 使用PinyinMatch库进行拼音匹配
        const pinyinMatch = 
          PinyinMatch.match(friend.nickname, query) || 
          (friend.remark && PinyinMatch.match(friend.remark, query));
          
        return directMatch || pinyinMatch;
      });
    })

    // 处理菜单选择
    const handleMenuSelect = (index) => {
      activeMenu.value = index
      if (index !== 'friends') {
        selectedFriend.value = null
      }
    }

    // 选择好友进行聊天
    const selectFriend = async (friend) => {
      console.log('选择好友:', friend)
      selectedFriend.value = friend
      // 重置分页数据
      messagePagination.page = 1
      messagePagination.hasMore = true
      // 加载消息记录
      fetchMessages(friend.userId, true)
      
      // 标记消息为已读并清除未读消息计数
      if (unreadMessages.value[friend.userId] && unreadMessages.value[friend.userId] > 0) {
        console.log(`标记好友[${friend.nickname}](ID:${friend.userId})的未读消息为已读, 未读数量:`, unreadMessages.value[friend.userId])
        try {
          await markMessagesAsRead(friend.userId)
          // 清除本地未读计数
          unreadMessages.value[friend.userId] = 0
          console.log('已清除本地未读计数')
        } catch (error) {
          console.error('标记消息为已读失败', error)
        }
      } else {
        console.log(`好友[${friend.nickname}](ID:${friend.userId})没有未读消息`)
      }
    }
    
    // 获取消息记录
    const fetchMessages = async (friendUserId, isRefresh = false) => {
      try {
        // 判断是否还有更多消息
        if (!messagePagination.hasMore && !isRefresh) {
          return
        }
        
        messageLoading.value = true
        
        // 如果是刷新，清空现有消息
        if (isRefresh) {
          messageList.value = []
          messagePagination.page = 1
        }
        
        const res = await getMessageList(friendUserId, messagePagination.page, messagePagination.size)
        console.log('获取到的消息记录:', res)
        
        // 处理获取到的消息记录
        let newMessages = []
        
        if (res && res.records && Array.isArray(res.records)) {
          // 将消息按时间顺序排序（从旧到新）
          newMessages = [...res.records].sort((a, b) => {
            return new Date(a.createTime) - new Date(b.createTime)
          })
          
          // 判断是否还有更多消息
          messagePagination.hasMore = res.records.length >= messagePagination.size
        } else if (res && Array.isArray(res)) {
          // 如果直接返回数组
          newMessages = [...res].sort((a, b) => {
            return new Date(a.createTime) - new Date(b.createTime)
          })
          
          // 判断是否还有更多消息
          messagePagination.hasMore = res.length >= messagePagination.size
        }
        
        // 确保每条消息都有status字段
        newMessages = newMessages.map(msg => {
          // 如果status不存在，则根据是否有readTime字段来判断已读状态
          if (typeof msg.status === 'undefined') {
            return {
              ...msg,
              status: msg.readTime ? 1 : 0
            }
          }
          return msg
        })
        
        // 保存旧消息滚动位置
        const chatMessagesEl = document.querySelector('.chat-messages')
        const oldScrollHeight = chatMessagesEl?.scrollHeight || 0
        const oldScrollTop = chatMessagesEl?.scrollTop || 0
        
        // 添加新消息
        if (isRefresh) {
          messageList.value = newMessages
          // 刷新时滚动到底部
          scrollToBottom()
        } else {
          // 加载更多历史消息时，添加到列表前面
          messageList.value = [...newMessages, ...messageList.value]
          
          // 恢复原来的滚动位置
          if (chatMessagesEl) {
            setTimeout(() => {
              const newScrollHeight = chatMessagesEl.scrollHeight
              chatMessagesEl.scrollTop = oldScrollTop + (newScrollHeight - oldScrollHeight)
            }, 50)
          }
        }
        
        // 加载完成后，如果是第一页，滚动到底部
        if (isRefresh) {
          scrollToBottom()
        }
        
        // 更新页码
        if (!isRefresh && messagePagination.hasMore) {
          messagePagination.page++
        }
      } catch (error) {
        ElMessage.error('获取消息记录失败')
        if (isRefresh) {
          messageList.value = []
        }
      } finally {
        messageLoading.value = false
      }
    }
    
    // 监听聊天窗口滚动，当滚动到顶部时加载更多消息
    const handleChatScroll = (event) => {
      const { scrollTop } = event.target
      // 当滚动到距离顶部50px以内，且不是正在加载中，且有更多消息时，加载更多
      if (scrollTop < 50 && !messageLoading.value && messagePagination.hasMore && selectedFriend.value) {
        fetchMessages(selectedFriend.value.userId)
      }
    }
    
    // 滚动到消息底部
    const scrollToBottom = () => {
      setTimeout(() => {
        const chatMessagesEl = document.querySelector('.chat-messages')
        if (chatMessagesEl) {
          chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight
        }
      }, 100)
    }

    // 发送消息
    const sendMessage = async () => {
      if (!messageText.value.trim() || !selectedFriend.value) return
      
      try {
        const messageData = {
          receiverUserId: selectedFriend.value.userId,
          content: messageText.value.trim(),
          msgType: MessageType.TEXT
        }
        
        // 先清空输入框，提升用户体验
        const tempMessage = messageText.value.trim()
        messageText.value = ''
        
        // 创建一个临时消息对象，用于立即显示在UI上
        const tempMessageObj = {
          id: 'temp-' + Date.now(),
          senderUserId: userInfo.id,
          receiverUserId: selectedFriend.value.userId,
          content: tempMessage,
          msgType: MessageType.TEXT,
          createTime: new Date().toISOString(),
          status: 0  // 0表示未读状态
        }
        
        // 添加临时消息到列表，立即显示
        messageList.value.push(tempMessageObj)
        
        // 滚动到底部
        scrollToBottom()
        
        try {
          // 发送消息到服务器
          const result = await sendMessageRequest(messageData)
          
          // 如果需要，可以根据返回结果更新临时消息
          if (result && result.id) {
            const index = messageList.value.findIndex(m => m.id === tempMessageObj.id)
            if (index !== -1) {
              // 确保保留未读状态
              messageList.value[index] = { 
                ...result,
                status: result.status !== undefined ? result.status : 0  // 如果服务器没有返回status，则默认为未读
              }
            }
          }
        } catch (sendError) {
          // 移除临时消息
          messageList.value = messageList.value.filter(m => m.id !== tempMessageObj.id)
          
          // 恢复消息文本
          messageText.value = tempMessage
          
          // 显示更具体的错误信息
          if (sendError.response && sendError.response.status === 302) {
            ElMessage.error('发送失败：请求被重定向，请检查API配置')
          } else {
            ElMessage.error('发送消息失败，请重试')
          }
        }
      } catch {
        ElMessage.error('发送消息失败')
      }
    }

    // 获取最新的用户信息
    const fetchUserInfo = async () => {
      try {
        loading.value = true
        const res = await getUserInfo()
        
        // 更新用户信息
        Object.assign(userInfo, res)
        
        // 更新编辑资料
        userProfile.tfId = res.tfId
        userProfile.nickname = res.nickname
        userProfile.avatar = res.avatar
        userProfile.gender = res.gender !== undefined ? res.gender : 1
        userProfile.searchEnabled = res.searchEnabled !== undefined ? res.searchEnabled : 1
        userProfile.signature = res.signature || '这个人很懒，什么都没留下'
      } catch {
        // API层已经显示了错误消息，这里不需要再次显示
      } finally {
        loading.value = false
      }
    }

    // 获取好友请求列表
    const fetchFriendRequests = async () => {
      try {
        requestLoading.value = true
        const res = await getFriendRequests()
        console.log('获取好友请求列表详情:', res)
        
        if (res && Array.isArray(res)) {
          friendRequests.value = res
        } else if (res && res.code === 1 && res.data) {
          friendRequests.value = res.data || []
        } else {
          friendRequests.value = []
        }
      } catch (error) {
        console.error('获取好友请求列表失败:', error)
        // API层已经显示了错误消息
        friendRequests.value = []
      } finally {
        requestLoading.value = false
      }
    }

    // 处理好友请求
    const handleFriendRequestAction = async (request, action) => {
      try {
        await handleFriendRequest(request.id, action)
        ElMessage.success(action === 'accept' ? '已接受好友请求' : '已拒绝好友请求')
        // 重新获取好友请求列表
        await fetchFriendRequests()
        // 如果是接受请求，刷新好友列表
        if (action === 'accept') {
          await fetchFriends()
        }
      } catch (error) {
        console.error('处理好友请求失败:', error)
        // API层已经显示了错误消息
      }
    }

    // 获取好友请求数量
    const fetchFriendRequestCount = () => {
      // 使用getFriendRequests而不是getFriendRequestCount，因为后端没有提供/friend/request/count接口
      getFriendRequests()
        .then(res => {
          // 处理各种格式的响应
          if (Array.isArray(res)) {
            // 如果直接返回数组，计算数组长度
            friendRequestCount.value = res.length
          } else if (res && res.records && Array.isArray(res.records)) {
            // 如果返回分页对象，计算records数组长度
            friendRequestCount.value = res.records.length
          } else if (res && typeof res.count === 'number') {
            // 如果返回包含count字段的对象
            friendRequestCount.value = res.count
          } else {
            // 默认设为0
            friendRequestCount.value = 0
          }
          console.log('获取到好友请求数量:', friendRequestCount.value)
        })
        .catch(error => {
          console.error('获取好友请求数量失败:', error)
          friendRequestCount.value = 0
        })
    }

    // 获取未读消息数
    const fetchUnreadMessageCount = async () => {
      try {
        const result = await getUnreadMessageCount()
        
        if (result) {
          // 处理返回格式: { unreadBySender: { "7": "20" }, totalUnread: "20" }
          const { unreadBySender } = result
          
          // 清空当前未读消息计数
          unreadMessages.value = {}
          
          // 将每个发送者的未读消息数添加到响应式对象中
          // 注意：后端返回的是字符串数字，需要转换为数字
          if (unreadBySender) {
            Object.keys(unreadBySender).forEach(senderId => {
              unreadMessages.value[senderId] = parseInt(unreadBySender[senderId]) || 0
            })
          }
        }
      } catch (error) {
        // 静默处理错误
      }
    }

    // 组件挂载时获取用户信息和好友列表
    onMounted(async () => {
      // 确保先获取用户信息和好友列表
      await fetchUserInfo()
      await fetchFriends()
      await fetchFriendRequestCount()
      await fetchUnreadMessageCount()  // 获取未读消息数
      
      // 设置定时器，每隔5分钟检查一次好友请求
      requestCheckTimer = setInterval(() => {
        fetchFriendRequestCount()
      }, 5 * 60 * 1000)
      
      // 添加WebSocket消息监听
      addMessageListener(handleWebSocketMessage);
    })
    
    // 组件卸载时清除定时器和监听器
    onUnmounted(() => {
      if (requestCheckTimer) {
        clearInterval(requestCheckTimer)
      }
      removeMessageListener(handleWebSocketMessage)
    })

    // 个人资料表单验证规则
    const profileRules = {
      tfId: [
        { required: true, message: '请输入TF ID', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      searchEnabled: [
        { required: true, message: '请选择搜索设置', trigger: 'change' }
      ],
      signature: [
        { max: 50, message: '个性签名不能超过50个字符', trigger: 'blur' }
      ]
    }

    // 保存个人资料
    const saveProfile = async () => {
      if (!profileFormRef.value) return
      
      try {
        // 表单验证
        await profileFormRef.value.validate()
        
        loading.value = true
        
        // 构建要更新的数据
        const profileData = {
          tfId: userProfile.tfId,
          nickname: userProfile.nickname,
          avatar: userProfile.avatar,
          gender: userProfile.gender,
          searchEnabled: userProfile.searchEnabled,
          signature: userProfile.signature
        }
        
        // 发送更新请求
        await updateProfile(profileData)
        
        // 更新成功后重新获取最新数据
        await fetchUserInfo()
        
        ElMessage.success('个人资料保存成功')
        showProfile.value = false
      } catch {
        // API层已经显示了错误消息，这里不需要再次显示
      } finally {
        loading.value = false
      }
    }

    // 退出登录
    const handleLogout = () => {
      ElMessageBox.confirm(
        '确定要退出登录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 关闭WebSocket连接
        closeWebSocket()
        
        // 清除登录信息
        localStorage.removeItem('token')
        localStorage.removeItem('userId')
        
        // 跳转到登录页
        router.push('/login')
        ElMessage.success('已退出登录')
      }).catch(() => {})
    }

    // 加载更多好友
    const loadMoreFriends = async () => {
      if (friendList.value.length >= pagination.total || loading.value) return
      
      pagination.page++
      try {
        loading.value = true
        const result = await getFriendList(pagination.page, pagination.size)
        if (result.records && result.records.length > 0) {
          friendList.value = [...friendList.value, ...result.records]
        }
      } catch (error) {
        pagination.page-- // 恢复页码
      } finally {
        loading.value = false
      }
    }

    // 搜索好友
    const handleSearch = async () => {
      if (!searchQuery.value.trim()) {
        searchResult.value = null
        return
      }
      
      try {
        searchLoading.value = true
        const result = await searchFriend(searchQuery.value.trim())
        searchResult.value = result
      } catch (error) {
        // API层已经显示了错误消息
      } finally {
        searchLoading.value = false
      }
    }

    // 关闭搜索对话框
    const closeSearchDialog = () => {
      if (searchResult.value) {
        // 如果已有搜索结果，则返回搜索界面
        searchResult.value = null
      } else {
        // 否则关闭对话框
        showSearchUserDialog.value = false
      }
      // 清空搜索词
      searchQuery.value = ''
    }

    // 添加好友
    const handleAddFriend = async (user) => {
      try {
        const { value: remark } = await ElMessageBox.prompt('请输入好友备注（可选）', '添加好友', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^.{0,20}$/,
          inputErrorMessage: '备注长度不能超过20个字符'
        })
        
        try {
          await addFriend(user.id, remark || '')
          ElMessage.success('好友请求发送成功')
          // 重新获取好友列表
          await fetchFriends()
        } catch (error) {
          if (error.response && error.response.data) {
            const { msg } = error.response.data
            ElMessage.warning(msg || '添加好友失败')
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          // API层已经显示了错误消息
        }
      }
    }

    // 查看好友请求
    const viewFriendRequests = () => {
      router.push('/friend-requests')
    }

    // 查看好友详情
    const viewFriendDetail = (friend) => {
      friendDetail.value = null
      showFriendDetail.value = true
      loadingFriendDetail.value = true
      
      getFriendInfo(friend.userId)
        .then(res => {
          friendDetail.value = res
        })
        .catch(() => {
          // API层已经显示了错误消息
        })
        .finally(() => {
          loadingFriendDetail.value = false
        })
    }

    // 处理好友操作命令
    const handleFriendCommand = (command, friend) => {
      switch (command) {
        case 'detail':
          viewFriendDetail(friend)
          break
        case 'remark':
          handleUpdateRemark(friend)
          break
        case 'delete':
          confirmDeleteFriend(friend)
          break
      }
    }

    // 修改好友备注
    const handleUpdateRemark = (friend) => {
      ElMessageBox.prompt(
        '请输入新的好友备注',
        '修改备注',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: friend.remark || '',
          inputPattern: /^.{0,20}$/,
          inputErrorMessage: '备注长度不能超过20个字符'
        }
      ).then(({ value }) => {
        updateFriendRemark(friend.userId, value)
          .then(() => {
            ElMessage.success('修改备注成功')
            // 更新本地数据
            const index = friendList.value.findIndex(item => item.userId === friend.userId)
            if (index !== -1) {
              friendList.value[index].remark = value
              // 如果是当前选中的好友，也更新选中的好友
              if (selectedFriend.value && selectedFriend.value.userId === friend.userId) {
                selectedFriend.value.remark = value
              }
            }
          })
          .catch(() => {
            // API层已经显示了错误消息
          })
      }).catch(() => {})
    }

    // 确认删除好友
    const confirmDeleteFriend = (friend) => {
      ElMessageBox.confirm(
        `确定要删除好友"${friend.remark || friend.nickname}"吗？`,
        '删除好友',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteFriend(friend.userId)
          .then(() => {
            ElMessage.success('删除好友成功')
            // 从列表中移除
            friendList.value = friendList.value.filter(item => item.userId !== friend.userId)
            // 如果当前选中的是被删除的好友，清除选中
            if (selectedFriend.value && selectedFriend.value.userId === friend.userId) {
              selectedFriend.value = null
            }
          })
          .catch(() => {
            // API层已经显示了错误消息
          })
      }).catch(() => {})
    }

    // 上传头像
    const uploadAvatar = () => {
      ElMessage.info('头像上传功能即将上线')
    }
    
    // 处理图片上传
    const handleUploadImage = async (file) => {
      if (!selectedFriend.value) return false
      
      try {
        // 显示上传加载提示
        ElMessage.info('正在上传图片...')
        
        const result = await uploadImage(file)
        
        // 检查返回结果
        if (result && result.url) {
          // 发送图片消息
          const messageData = {
            receiverUserId: selectedFriend.value.userId,
            content: result.url,
            msgType: MessageType.IMAGE,
            fileName: file.name,
            fileSize: file.size
          }
          
          // 创建临时消息对象显示
          const tempMessageObj = {
            id: 'temp-img-' + Date.now(),
            senderUserId: userInfo.id,
            receiverUserId: selectedFriend.value.userId,
            content: result.url,
            msgType: MessageType.IMAGE,
            fileName: file.name,
            fileSize: file.size,
            createTime: new Date().toISOString(),
            status: 0
          }
          
          // 添加临时消息
          messageList.value.push(tempMessageObj)
          
          // 滚动到底部
          scrollToBottom()
          
          // 发送消息到服务器
          await sendMessageRequest(messageData)
          
          ElMessage.success('图片发送成功')
        } else {
          ElMessage.error('图片上传失败')
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        ElMessage.error('图片上传失败')
      }
      
      return false // 阻止默认上传行为
    }
    
    // 处理文件上传
    const handleUploadFile = async (file) => {
      if (!selectedFriend.value) return false
      
      try {
        // 显示上传加载提示
        ElMessage.info('正在上传文件...')
        
        const result = await uploadFile(file)
        
        // 检查返回结果
        if (result && result.url) {
          // 发送文件消息
          const messageData = {
            receiverUserId: selectedFriend.value.userId,
            content: result.url,
            msgType: MessageType.FILE,
            fileName: file.name,
            fileSize: file.size
          }
          
          // 创建临时消息对象显示
          const tempMessageObj = {
            id: 'temp-file-' + Date.now(),
            senderUserId: userInfo.id,
            receiverUserId: selectedFriend.value.userId,
            content: result.url,
            msgType: MessageType.FILE,
            fileName: file.name,
            fileSize: file.size,
            createTime: new Date().toISOString(),
            status: 0
          }
          
          // 添加临时消息
          messageList.value.push(tempMessageObj)
          
          // 滚动到底部
          scrollToBottom()
          
          // 发送消息到服务器
          await sendMessageRequest(messageData)
          
          ElMessage.success('文件发送成功')
        } else {
          ElMessage.error('文件上传失败')
        }
      } catch (error) {
        console.error('上传文件失败:', error)
        ElMessage.error('文件上传失败')
      }
      
      return false // 阻止默认上传行为
    }
    
    // 下载文件
    const downloadFile = (fileUrl, fileName) => {
      try {
        // 创建一个临时链接
        const link = document.createElement('a')
        link.href = fileUrl.startsWith('http') ? fileUrl : getFileUrl(fileUrl)
        link.target = '_blank'
        link.download = fileName || '未命名文件'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        console.error('下载文件失败:', error)
        ElMessage.error('下载文件失败')
      }
    }
    
    // 格式化文件大小
    const formatFileSize = (size) => {
      if (!size) return ''
      
      const units = ['B', 'KB', 'MB', 'GB']
      let formattedSize = size
      let unitIndex = 0
      
      while (formattedSize >= 1024 && unitIndex < units.length - 1) {
        formattedSize /= 1024
        unitIndex++
      }
      
      return `${formattedSize.toFixed(2)} ${units[unitIndex]}`
    }
    
    // 处理接收到的WebSocket消息
    const handleWebSocketMessage = (data) => {
      console.log('收到WebSocket消息:', data)
      try {
        if (!data) {
          return
        }
        
        // 检查是否是消息已读状态通知
        if (data === 'READ_ACK') {
          console.log('收到消息已读通知，准备更新消息状态')
          
          // 由于data就是一个字符串，需要更新所有发送的消息为已读
          if (selectedFriend.value && messageList.value.length > 0) {
            let updatedCount = 0
            
            // 找出所有由当前用户发送给当前选中好友的消息
            const messageIndicesToUpdate = []
            messageList.value.forEach((msg, index) => {
              if (msg.senderUserId == userInfo.id && 
                  msg.receiverUserId == selectedFriend.value.userId && 
                  msg.status !== 1) {
                messageIndicesToUpdate.push(index)
              }
            })
            
            // 更新这些消息的状态
            messageIndicesToUpdate.forEach(index => {
              const updatedMessage = { ...messageList.value[index], status: 1 }
              messageList.value.splice(index, 1, updatedMessage)
              updatedCount++
            })
            
            console.log(`成功更新了${updatedCount}条消息的已读状态`)
          } else {
            console.warn('收到READ_ACK消息，但当前没有选择好友或没有消息')
          }
          
          return
        }
        
        // 强制转换ID为字符串，确保比较一致性
        const msgId = data.id ? String(data.id) : null
        const senderId = data.senderUserId ? String(data.senderUserId) : null
        
        if (!msgId || !senderId) {
          console.warn('消息缺少必要字段id或senderUserId:', data)
          return
        }
        
        console.log('发送者ID:', senderId, '类型:', typeof senderId)
        console.log('当前未读消息对象:', unreadMessages.value)
        
        // 判断是否正在与发送者聊天
        const isChatting = selectedFriend.value && String(selectedFriend.value.userId) === senderId
        
        // 处理各种类型的消息（文本、图片等）
        // 如果当前正在与发送者聊天，直接添加消息到列表并标记为已读
        if (isChatting) {
          console.log('正在与发送者聊天，标记为已读')
          // 检查消息是否已存在(避免重复)
          const existingMsgIndex = messageList.value.findIndex(m => String(m.id) === msgId)
          if (existingMsgIndex === -1) {
            // 根据消息类型处理
            const messageObj = {
              ...data,
              // 确保图片消息和其他类型消息都有正确的字段
              msgType: data.msgType ? Number(data.msgType) : MessageType.TEXT,
              content: data.content || '',
              fileName: data.fileName || '',
              fileSize: data.fileSize || 0,
              status: 0 // 默认为未读状态
            }
            
            // 使用解构拷贝确保Vue响应式更新
            const newMessageList = [...messageList.value]
            newMessageList.push(messageObj)
            messageList.value = newMessageList
            
            // 滚动到底部
            scrollToBottom()
            
            // 自动标记为已读
            markMessagesAsRead(senderId).catch(error => {
              console.error('标记消息为已读失败', error)
            })
          }
        } else {
          console.log('不是当前聊天对象，增加未读计数')
          // 如果不是当前聊天好友，增加未读计数
          if (!unreadMessages.value[senderId]) {
            unreadMessages.value[senderId] = 0
          }
          unreadMessages.value[senderId]++
          
          console.log('更新后的未读消息:', unreadMessages.value)
          
          // 提示新消息 (只有在不是当前聊天对象时才显示通知)
          const sender = friendList.value.find(f => String(f.userId) === senderId)
          if (sender) {
            console.log('找到发送者:', sender.nickname)
            // 根据消息类型显示不同的提示
            const msgType = data.msgType ? parseInt(data.msgType) : MessageType.TEXT
            const msgTypeText = msgType === MessageType.IMAGE ? '图片' : 
                               msgType === MessageType.FILE ? '文件' : 
                               msgType === MessageType.VOICE ? '语音' : 
                               msgType === MessageType.VIDEO ? '视频' : '消息'
            
            ElMessage({
              message: `收到来自 ${sender.remark || sender.nickname} 的新${msgTypeText}`,
              type: 'info',
              duration: 3000
            })
          } else {
            console.log('未找到发送者，当前好友列表:', friendList.value)
          }
        }
      } catch (error) {
        console.error('处理WebSocket消息失败', error)
      }
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      try {
        const date = new Date(dateString);
        // 判断是否是今天
        const today = new Date();
        const isToday = date.getDate() === today.getDate() && 
                        date.getMonth() === today.getMonth() && 
                        date.getFullYear() === today.getFullYear();

        if (isToday) {
          // 如果是今天，只显示时间
          return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        } else {
          // 否则显示日期和时间
          return date.toLocaleString('zh-CN', {
            month: 'numeric',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
          });
        }
      } catch {
        return dateString;
      }
    }

    // 手动加载更多消息
    const loadMoreMessages = () => {
      if (selectedFriend.value && !messageLoading.value && messagePagination.hasMore) {
        fetchMessages(selectedFriend.value.userId)
      }
    }

    return {
      activeMenu,
      showProfile,
      userInfo,
      userProfile,
      loading,
      friendList,
      selectedFriend,
      searchQuery,
      messageText,
      menuLabels,
      filteredFriends,
      profileFormRef,
      profileRules,
      showAddFriendDialog,
      handleMenuSelect,
      selectFriend,
      sendMessage,
      uploadAvatar,
      saveProfile,
      handleLogout,
      fetchUserInfo,
      fetchFriends,
      pagination,
      loadMoreFriends,
      searchResult,
      searchLoading,
      handleSearch,
      handleAddFriend,
      friendSearchQuery,
      friendRequests,
      requestLoading,
      fetchFriendRequests,
      handleFriendRequestAction,
      viewFriendRequests,
      friendRequestCount,
      fetchFriendRequestCount,
      handleFriendCommand,
      confirmDeleteFriend,
      handleUpdateRemark,
      viewFriendDetail,
      friendDetail,
      showFriendDetail,
      loadingFriendDetail,
      messageList,
      messageLoading,
      formatDate,
      scrollToBottom,
      unreadMessages,
      handleChatScroll,
      messagePagination,
      loadMoreMessages,
      showSearchUserDialog,
      closeSearchDialog,
      MessageType,
      handleUploadImage,
      handleUploadFile,
      downloadFile,
      formatFileSize
    }
  }
}
</script>

<style scoped>
.home-container {
  display: flex;
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 280px;
  height: 100%;
  background: #fff;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.user-profile {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.avatar {
  margin-right: 15px;
}

.user-info {
  flex: 1;
}

.nickname {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.tf-id {
  font-size: 12px;
  color: #999;
}

.menu {
  flex: 1;
  border-right: none;
}

.menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
}

.menu :deep(.el-menu-item.is-active) {
  background-color: rgba(118, 75, 162, 0.1);
  color: #764ba2;
}

.menu :deep(.el-menu-item:hover) {
  background-color: rgba(118, 75, 162, 0.05);
}

.logout {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  color: #f56c6c;
  cursor: pointer;
}

.logout .el-icon {
  margin-right: 10px;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  display: flex;
  height: 100%;
  background-color: #f9f9f9;
  position: relative;
}

/* 好友列表 */
.friend-list {
  width: 300px;
  height: 100%;
  background: #fff;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.friend-list-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.friend-actions-header {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.friend-search {
  width: 100%;
}

.friend-list-content {
  flex: 1;
  overflow-y: auto;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}

.friend-item:hover {
  background-color: #f9f9f9;
}

.friend-item.active {
  background-color: rgba(118, 75, 162, 0.1);
}

.avatar-container {
  position: relative;
}

.unread-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  z-index: 1;
}

.friend-info {
  flex: 1;
  margin-left: 10px;
}

.friend-name {
  font-size: 15px;
  color: #333;
  margin-bottom: 3px;
  display: flex;
  align-items: center;
}

.friend-status {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.friend-actions {
  display: flex;
  align-items: center;
}

.friend-more {
  color: #999;
  cursor: pointer;
}

/* 聊天区域 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  height: 65px;
  background: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
}

.chat-toolbar {
  display: flex;
  gap: 20px;
}

.chat-toolbar .el-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
}

.chat-input-area {
  background: #fff;
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
}

.toolbar .el-icon {
  font-size: 20px;
  color: #666;
  cursor: pointer;
}

.chat-input-area .el-button {
  align-self: flex-end;
  margin-top: 10px;
  background: linear-gradient(to right, #667eea, #764ba2);
  border: none;
}

/* 空聊天区域 */
.empty-chat {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.empty-chat-content {
  text-align: center;
  color: #999;
}

.empty-icon {
  margin-bottom: 15px;
  color: #ddd;
}

/* 其他功能占位内容 */
.placeholder-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 个人资料弹窗 */
.profile-content {
  padding: 20px 0;
}

.profile-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.avatar-upload {
  margin-top: 15px;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #764ba2;
  --el-button-border-color: #764ba2;
  --el-button-hover-bg-color: #8a63b1;
  --el-button-hover-border-color: #8a63b1;
  --el-button-active-bg-color: #673d91;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #764ba2;
  border-color: #764ba2;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #764ba2;
}

.load-more {
  text-align: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.load-more .el-button {
  width: 100%;
  display: block;
  color: #764ba2;
}

.el-empty {
  padding: 40px 0;
}

/* 搜索结果区域样式 */
.search-result-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f9f9f9;
}

.search-result-content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.search-result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-result-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.search-result-item {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-result-info {
  flex: 1;
  margin-left: 20px;
}

.search-result-name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 10px;
}

.search-result-tfid {
  font-size: 14px;
  color: #999;
  margin-left: 10px;
}

.search-result-email {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.search-result-signature {
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
  font-style: italic;
}

.search-result-actions {
  margin-top: 15px;
}

/* 好友请求列表样式 */
.friend-requests {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.friend-requests-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.friend-requests-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.empty-requests {
  padding: 30px;
}

.request-items {
  padding: 10px;
}

.request-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.request-item:last-child {
  border-bottom: none;
}

.request-info {
  flex: 1;
  margin-left: 15px;
}

.request-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.request-tfid {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

.request-email {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.request-time {
  font-size: 12px;
  color: #999;
}

.request-actions {
  margin-left: 15px;
}

.request-actions .el-button {
  margin-left: 10px;
}

/* 好友请求徽章样式 */
.friend-request-btn {
  position: relative;
}

.request-badge {
  position: absolute !important;
  top: -8px !important;
  right: -8px !important;
  transform: translate(0, 0) !important;
}

/* 好友详情弹窗样式 */
.friend-detail-content {
  padding: 20px 0;
}

.friend-detail-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.friend-detail-info {
  padding: 0 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.label {
  font-weight: 500;
}

.value {
  margin-left: 10px;
}

.friend-detail-form {
  padding: 0 20px;
}

.friend-detail-form .el-form-item {
  margin-bottom: 20px;
}

.friend-detail-form .el-form-item label {
  font-weight: 500;
}

.friend-detail-form .el-form-item .el-input {
  width: 100%;
}

.friend-detail-form .el-form-item .el-button {
  width: 100%;
  background: linear-gradient(to right, #667eea, #764ba2);
  border: none;
  color: #fff;
}

.friend-detail-form .el-form-item .el-button:hover {
  background: linear-gradient(to right, #8a63b1, #a270b8);
}

/* 消息列表样式 */
.message-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px;
}

.message-item {
  display: flex;
  align-items: flex-start;
  max-width: 70%;
}

.message-item.self {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-item.other {
  align-self: flex-start;
}

.message-content {
  margin: 0 10px;
  background: #fff;
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}

.message-item.self .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  overflow: hidden;
  border-radius: 8px;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.self .read-status {
  color: rgba(255, 255, 255, 0.7);
}

.self .message-time {
  justify-content: flex-end;
}

.chat-placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

/* 加载更多消息样式 */
.load-more-messages {
  width: 100%;
  text-align: center;
  padding: 10px 0;
  margin-bottom: 10px;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

.loading-icon {
  animation: rotate 1s linear infinite;
  margin-right: 5px;
}

.load-more-btn {
  color: #764ba2;
  font-size: 13px;
  cursor: pointer;
  padding: 5px 0;
}

.load-more-btn:hover {
  color: #667eea;
}

.search-user-form {
  padding: 20px 0;
}

.search-tip {
  margin-bottom: 15px;
  color: #666;
}

.search-input {
  width: 100%;
}

.search-result-container {
  padding: 20px 0;
}

.search-result-user {
  display: flex;
  margin-bottom: 20px;
}

.search-result-info {
  margin-left: 20px;
  flex: 1;
}

.search-result-name {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
}

.search-result-tfid {
  font-size: 14px;
  color: #999;
  margin-left: 10px;
}

.search-result-email {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.search-result-signature {
  font-size: 14px;
  color: #999;
  margin-bottom: 15px;
  font-style: italic;
}

.search-result-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 已读状态样式 */
.read-status {
  font-size: 12px;
  margin-left: 8px;
  color: #909399;
  display: inline-block;
  transition: all 0.3s;
}

/* 消息已读和未读状态样式差异 */
.read-status:not([data-read="true"]) {
  color: #95a5a6;
}

/* 调整时间和已读状态的显示 */
.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

/* 控制已读状态位置 */
.self .message-time {
  justify-content: flex-end;
}

/* 其他人发送的消息样式调整 */
.other .message-time {
  color: #909399;
}

/* 自己发送的消息样式调整 */
.self .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.self .read-status {
  color: rgba(255, 255, 255, 0.7);
}

/* 图片消息样式 */
.message-image {
  max-width: 200px;
  max-height: 200px;
  overflow: hidden;
  border-radius: 8px;
}

/* 文件消息样式 */
.message-file {
  max-width: 300px;
}

.file-container {
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.self .file-container {
  background: rgba(255, 255, 255, 0.2);
}

.file-container:hover {
  background: rgba(0, 0, 0, 0.1);
}

.self .file-container:hover {
  background: rgba(255, 255, 255, 0.3);
}

.file-container .el-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #764ba2;
}

.self .file-container .el-icon {
  color: white;
}

.file-info {
  flex: 1;
  overflow: hidden;
}

.file-name {
  font-size: 14px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: 12px;
  color: #999;
}

.self .file-size {
  color: rgba(255, 255, 255, 0.7);
}

/* 上传按钮样式 */
.upload-button {
  display: contents;
}

.upload-button .el-icon {
  font-size: 20px;
  color: #666;
  cursor: pointer;
}
</style> 